<template>
  <div>
    <!-- <el-button @click="detailInfo={}, showDetail=true" type="text" size="small">测试</el-button> -->
    <el-card v-show="!showDetail">
      <div class="select_box">
        <el-row>
          <el-col :span="7">
            <div class="title">工程名称</div>
            <el-input style="width:80%" v-model="selectInfo.name" size="small" placeholder="请输入"></el-input>
          </el-col>
          <el-col :span="7">
            <div class="title">工程编号</div>
            <el-input style="width:80%" v-model="selectInfo.number" size="small" placeholder="请输入"></el-input>
          </el-col>
          <el-col :span="7">
            <div class="title">地点</div>
            <el-input style="width:80%" v-model="selectInfo.location" size="small" placeholder="请输入"></el-input>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px;">
          <el-col :span="7">
            <div class="title">提交审批时间</div>
            <el-date-picker
              style="width:80%"
              v-model="selectInfo.date"
              size="small"
              type="daterange"
              format="yyyy-MM-dd"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :span="7">
            <div class="title">状态</div>
            <el-select style="width:80%" v-model="selectInfo.status" clearable size="small" placeholder="请选择">
              <el-option 
                v-for="item in selectStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row> 
        <el-row style="margin-top: 10px;">
          <el-col :span="24">
            <el-button size="small" @click="reset">重置</el-button>
						<el-button type="primary" size="small" @click="handleChangePage">筛选</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="table_box">
        <el-table ref="multipleTable" :data="tableData" v-loading="loading">
          <el-table-column prop="name" label="工程名称">
          </el-table-column>
          <el-table-column prop="code" label="工程编号">
          </el-table-column>
          <el-table-column prop="leaderName" label="工作负责人">
          </el-table-column>
          <el-table-column prop="updStatus" label="上传状态">
            <template slot-scope="scope">
              {{ scope.row.attachment ? '已上传' : '未上传' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="审核状态">
            <template slot-scope="scope">
              {{ statusList[scope.row.status] }}
            </template>
          </el-table-column>
          <el-table-column prop="jobTicketTime" :formatter="dateFormat" label="开票时间">
            <template slot-scope="scope">
              {{ dateFormat(scope.row.jobTicketTime) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="220" v-if="type==='list'">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="exportJob(scope.row)">导出</el-button>
              <div style="display: inline-block;">
                <el-upload
                  style="margin: 0 10px;"
                  class="upload-demo"
                  action="" 
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleUpload"
                  :on-success="handleSuccess">
                  <el-button type="text" size="small" :disabled="scope.row.status===1 || scope.row.status===2" @click="importJobId=scope.row.ticketId">上传</el-button>
                </el-upload>
              </div>
              <el-button type="text" size="small" :disabled="scope.row.status===1 || scope.row.status===2"  @click="submit(scope.row.ticketId)">提交审核</el-button>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200" v-else>
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="officeOnline(scope.row.attachment)">详情</el-button>
              <div style="display: inline-block;" >
                <el-popconfirm
                  style="margin-left: 10px;"
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  icon-color="#67c23a"
                  title="是否通过该审核？"
                  @confirm="process(scope.row.ticketId, 2)">
                  <el-button type="text" size="small" :disabled="scope.row.status!=1" slot="reference">通过</el-button>
                </el-popconfirm>
                <el-popconfirm
                  style="margin-left: 10px;"
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  icon-color="red"
                  title="是否拒绝该审核？"
                  @confirm="process(scope.row.ticketId, 3)">
                  <el-button type="text" :style="scope.row.status!=1 ? 'color: #C0C4CC;' : 'color: red;'" size="small" :disabled="scope.row.status!=1" slot="reference">拒绝</el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="footer">
          <el-pagination @current-change="handleChangePage" :current-page.sync="page" :page-size="pageSize" layout="prev, pager, next" :total="total"></el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 交底单详情 -->
    <el-drawer
			:title="'交底单 — ' + detailInfo.name"
			:visible.sync="showDetail"
      :wrapperClosable="false"
			size="80%"
			:direction="'rtl'">
      <detail v-if="showDetail" @back="back" :detailId="detailInfo.surveyId" :type="type"></detail>
    </el-drawer>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index.js'
import Detail from './detailView.vue'
import { getJobPage, submitJob, auditJob, saveAttachments, exportJobTicket } from '@/api/jobTicket/index.js'
import { getDic } from '@/api/utils/index'
export default {
  name: 'workList',
  components: {
    Detail
  },
  props:{
    type:{
      type: String
    }
  },
  data() {
    return {
      elLoading: false,
      showDetail: false,
      importJobId: null,
      detailInfo: {},
      tableData: [],
      selectStatus: [],
      statusList: {},
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      selectInfo: {
        name: '',
        number: '',
        date: [],
        location: '',
        status: null
      },
    }
  },
  mounted() {
    this.getDicList()
    this.handleChangePage()
    
  },
  methods: {
    getDicList() {
      getDic('jobTicketStatus').then(res => {
        this.statusList = res.data
        for (let i in res.data) {
          this.selectStatus.push({
            value: parseInt(i),
            label: res.data[i]
          });
        }
      })
    },
    back(refresh) {
      this.showDetail = false
      if(refresh) this.handleChangePage()
    },
    reset() {
      this.selectInfo = {
        name: '',
        number: '',
        date: [],
        location: '',
        status: null
      }
    },
    handleChangePage() {
      this.loading = true
      let params = {...this.selectInfo, pageNum: this.page, pageSize: this.pageSize}
      if(params.date && params.date.length > 0) {
        params.submitStartTime = params.date[0]
        params.submitEndTime = params.date[1]
      }
      getJobPage(params).then(res => {
        this.total = res.data.total
        this.tableData = res.data.list
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },

    //审核
    process(id, status) {
      auditJob({
        bizId: id,
        toStatus: status
      }).then(res=> {
        this.$message.success('操作成功')
        this.handleChangePage()
      })
    },

    //打开详情 预览功能
    officeOnline(url) {
      if(!url) {
        this.$message.warning('改交底单未上传附件，无法预览！')
        return
      }
      if(url.indexOf('.pdf') != -1) {
        window.open(url)
      } else if(url.indexOf('.docx') != -1){
        url = 'https://view.officeapps.live.com/op/view.aspx?src=' + url
        window.open(url)
      } else {
        this.$message.warning('上传附件存在异常，无法预览！')
      }
    },
    //提交审核
    submit(id) {
      let ids = []
      if(!id) return
      ids = [id]
      submitJob(ids).then(res => {
        this.$message.success('提交成功')
        this.handleChangePage()
      })
    },
    //导出交底单
    exportJob(row) {
      if(!row.ticketId) return
      // if(row.attachment && row.attachment.indexOf('http') != -1) {
      //   if(row.attachment.indexOf('.pdf') != -1) {
      //     window.open(row.attachment)
      //   } else {
      //     window.location.href = row.attachment
      //   }
      //   return
      // }

      let params = {id: row.ticketId}
      this.openLoading()
      exportJobTicket(params).then(res => {
        let blob = res
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = row.typeName ? row.typeName + '.docx' : '交底单' + '.docx'
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        this.closeLoading()
      }).catch(error => {
        this.closeLoading()
      })
    },

    beforeAvatarUpload(file) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (fileType === 'pdf' || fileType === 'docx') {
          console.log('file');
      } else {
        this.$message.error("文件类型必须为docx或pdf格式")
        return false
      }
    },
    //图片上传
    handleUpload(option) {
      this.$ossUpload({
        path: option.file.name,
        file: option.file,
        folder: "ticket",
        done: res => {
          let fileUrl = res.res.requestUrls[0].split("?")[0];
          option.onSuccess(fileUrl)
        },
        fail: err => {
          console.log(err)
        }
      });
    },
    handleSuccess(res, file) {
      saveAttachments({
        id: this.importJobId,
        attachment: res
      }).then(res=>{
        this.$message.success("上传成功")
        this.handleChangePage()
      })
    },

    dateFormat(date) {
      if(date) {
        return parseTime(date,'{y}-{m}-{d}')
      } else {
        return '-'
      }
    },
    openLoading(){
      this.elLoading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    closeLoading(){
      this.elLoading.close();
    },
  }
}
</script>

<style lang="scss" scoped>
.select_box {
  .title {
    font-size: 15px;
    margin-bottom: 10px;
  }
}
.table_box {
  .footer {
    margin-top: 10px;
    text-align: center;
  }
}
</style>
